package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.ProListMapper;

import com.indusfo.spc.mapper.ProductlineMapper;
import com.indusfo.spc.mapper.StationMapper;
import com.indusfo.spc.mapper.UploadMapper;

import com.indusfo.spc.pojo.Productline;
import com.indusfo.spc.pojo.Workshop;
import com.indusfo.spc.service.ProductLineService;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.security.util.Length;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 产线业务层
 *
 * @author xuz
 * @date 2018/11/30 2:07 PM
 */
@Service
public class ProductLineServiceImpl implements ProductLineService {

    private  static  final Logger logger = LoggerFactory.getLogger(ProductLineServiceImpl.class);

    private static final int CAPACITYLENGTH=10;
    private static final int CONTENTLENGTH=50;
    @Resource
    private ProductlineMapper productLineMapper;

    @Resource
    private StationMapper stationMapper;

    /*@Resource
    private ProListMapper proListMapper;*/


    @Resource
    private UploadMapper uploadMapper;


    /**
     * 更新产线
     * @param lProductionLineId
     * @param vcRemark
     * @param vcProductionLineName
     * @param vcProductionLineCode
     * @param workshopId
     * @param capacity
     * @return com.indusfo.spc.vo.JSONObject
     */
    @Override
    @Transactional
    public JSONObject updateProductLine(String lProductionLineId, String vcRemark, String vcProductionLineName, String vcProductionLineCode, String workshopId, String capacity ) {
        Productline productLine=new Productline();

        if(!StringUtils.isBlank(capacity)){
            if(StringUtils.isNumeric(capacity)){
                if(capacity.length()>CAPACITYLENGTH){
                    throw new ParamsErrorException("产能数字过大！");
                }
                productLine.setCapacityNum(Integer.valueOf(capacity));
            }else {
                throw new ParamsErrorException("产能只能是数字！");
            }
        }
        if(StringUtils.isBlank(vcRemark)) {
            vcRemark = "";
        }
        if(StringUtils.isBlank(lProductionLineId)){
            throw new ParamsErrorException("产线Id不能为空");
        }
        if(StringUtils.isBlank(vcProductionLineName)){
            throw new ParamsErrorException("产线名称不能为空");
        }
        if(StringUtils.isBlank(vcProductionLineCode)){
            throw new ParamsErrorException("产线编码不能为空");
        }
        if(StringUtils.isBlank(workshopId)){
            throw new ParamsErrorException("车间ID不能为空");
        }
        productLine.setProductlineId(Integer.parseInt(lProductionLineId));
        productLine.setRemark(vcRemark);
        productLine.setProductlineCode(vcProductionLineCode);
        productLine.setProductlineName(vcProductionLineName);
        productLine.setWorkshopId(Integer.parseInt(workshopId));
        try {
            if(productLine.getProductlineId() == null) {
                throw new ParamsErrorException("请选择要修改的产线资料id");
            }

            checkParam(productLine, vcRemark);
            checkNoRepate(productLine);

            int	row = productLineMapper.updateByPrimaryKeySelective(productLine);

            if(row == 0) {
                throw new ModifyFailedException("数据更新失败！");
            }
            int stationFlag = stationMapper.updateStationWorkshopIdByProductionLineId(Integer.parseInt(workshopId),Integer.parseInt(lProductionLineId));

            return JSONObject.oK("更新成功！");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 新增
     *
     * @author xuz
     * @date 2018/11/30 2:08 PM
     * @param vcRemark
     * @return com.indusfo.spc.vo.JSONObject
     */

    @Override
    public JSONObject insertProductLine(String vcRemark, String vcProductionLineName, String vcProductionLineCode, String workshopId, String capacity) {
        Productline productLine=new Productline();


        if(vcRemark == null) {
            vcRemark="";
        }
        productLine.setRemark(vcRemark);
        if(StringUtils.isBlank(capacity)){

            if(StringUtils.isNumeric(capacity)){
                if(capacity.length()>CAPACITYLENGTH){
                    throw new ParamsErrorException("产能数字过大！");
                }
                productLine.setCapacityNum(Integer.valueOf(capacity));
            }else {
                throw new ParamsErrorException("产能只能是数字！");
            }

        }
        try {

            if(vcProductionLineName==null){
                throw new ParamsErrorException("产线名称不能为空");
            }
            if(vcProductionLineCode==null){
                throw new ParamsErrorException("产线编码不能为空");
            }
            if(workshopId==null){
                throw new ParamsErrorException("车间ID不能为空");
            }
            productLine.setProductlineCode(vcProductionLineCode);
            productLine.setProductlineName(vcProductionLineName);
            if(StringUtils.isNumeric(workshopId)){
                productLine.setWorkshopId(Integer.parseInt(workshopId));
            }
            checkParam(productLine, vcRemark);
            checkNoRepate(productLine);
            int	row = productLineMapper.insertSelective(productLine);

            if(row == 0) {
                throw new ModifyFailedException("数据新增失败！");
            }
            return JSONObject.oK("新增成功！");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 查询
     *
     * @author xuz
     * @date 2018/11/30 2:08 PM
     * @param productLine
     * @return com.indusfo.spc.vo.JSONObject
     */
    @Override
    public JSONObject queryProductLine(Productline productLine) {
        List<Productline> listProductLines = null;
        try {
            Integer pagesize = productLine.getPagesize();
            Integer pageindex = productLine.getPageindex();
            if(pagesize != null && pageindex != null) {
                productLine.setIncept(pagesize*(pageindex - 1));
            }
            Integer lProductLineId = productLine.getProductlineId();
            //如果有id,则查询单个产线信息
            if(lProductLineId != null) {
                listProductLines = productLineMapper.queryByProductLineId(lProductLineId);
            } else{  //查询多个sop管理信息
                listProductLines = productLineMapper.queryProductLineList(productLine);
            }
            if (listProductLines.isEmpty()) {
                return JSONObject.oK("没有查询到相关数据", listProductLines, 0);
            }
            //查询分页总记录数
            int count = productLineMapper.countProductLine(productLine);
            return JSONObject.oK("查询成功", listProductLines, count);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 删除
     *
     * @author xuz
     * @date 2018/11/30 2:08 PM
     * @param lProductLineIds
     * @param lDataState
     * @return com.indusfo.spc.vo.JSONObject
     */
    @Override
    public JSONObject deleteProductLine(Long[] lProductLineIds, Integer lDataState) {
        try {
            if(lDataState == null) {
                throw new ParamsErrorException("数据状态不能为空");
            }else if(lDataState != 1 && lDataState != 2 && lDataState != 3) {
                throw new ParamsErrorException("数据状态错误");
            }
            if (lProductLineIds == null || lProductLineIds.length==0) {
                throw new ParamsErrorException("请选择要删除的产线");
            }

            if(lDataState==2){
                int stationCount = stationMapper.listStationByProductLineId(lProductLineIds);
                if(stationCount>0){
                    throw new ParamsErrorException("所选产线含有工位无法删除");
                }
            }
            // 执行存储过程
            int row = productLineMapper.delteProductLine(lProductLineIds, lDataState);
            String msg = "";
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (lDataState) {
                    case 1:
                        throw new ModifyFailedException("启用失败");
                    case 2:
                        throw new ModifyFailedException("删除失败");
                    case 3:
                        throw new ModifyFailedException("停用失败");
                    default:
                }
            } else {
                switch (lDataState) {
                    case 1:
                        msg = "启用成功";break;
                    case 2:
                        msg = "删除成功";break;
                    case 3:
                        msg = "停用成功";break;
                    default:
                }
            }
            stationMapper.updateStationByProductionLineId(lProductLineIds,lDataState);
//            proListMapper.updateProListByProductionLineId(lProductLineIds,lDataState);
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public Productline getByProductLineCode(String vcProductionLineCode, Integer lProductionLineId) {
        return productLineMapper.queryByProductLineCode(vcProductionLineCode, lProductionLineId);
    }

    /**
     * 参数校验
     *
     * @author xuz
     * @date 2018/11/30 2:07 PM
     * @param productLine
     * @param vcRemark
     * @return void
     */
    private void checkParam(Productline productLine, String vcRemark) {
        if(StringUtils.isEmpty(productLine.getProductlineCode())) {
            throw new ParamsErrorException("产线编码不能为空");
        }

        if(getByProductLineCode(productLine.getProductlineCode(), productLine.getProductlineId()) != null){
            throw new ParamsErrorException("产线编码已存在");
        }
        if(StringUtils.isEmpty(productLine.getProductlineName())) {
            throw new ParamsErrorException("产线名称不能为空");
        }


        if(productLine.getWorkshopId() == null){
            throw new ParamsErrorException("请选择车间");
        }
        if(productLine.getProductlineCode().length() > CONTENTLENGTH) {
            throw new ParamsErrorException("产线编码字数超过规定长度50");
        }
        if(productLine.getProductlineName().length() > CONTENTLENGTH) {
            throw new ParamsErrorException("产线名称字数超过规定长度50");
        }
        if(vcRemark.length() > CONTENTLENGTH) {
            throw new ParamsErrorException("说明字数超过规定长度50");
        }

        // if(productLine.getCapacity()>){}
    }

    /**
     * 根据产线名称去重
     * @param productLine
     * @return
     */
    public void checkNoRepate(Productline productLine){
        int  count=productLineMapper.countProductLine(productLine);
        if(count>0){
            throw  new ParamsErrorException("产线名称已存在");
        }
    }
    @Override
    public List<Productline> getByWorkshopId(Integer workshopId) {
        // TODO Auto-generated method stub
        return productLineMapper.queryByWorkshopId(workshopId);
    }

    @Override
    public String checkExcelContent(Productline productLine){

        String vcRemark = productLine.getRemark();
        if(StringUtils.isBlank(productLine.getProductlineCode()) && StringUtils.isBlank(productLine.getProductlineName()) &&
                StringUtils.isBlank(productLine.getWorkshopName()) && StringUtils.isBlank(productLine.getRemark()) && StringUtils.isBlank(productLine.getCapacityNum().toString())){
            return "该行数据为空:数据为彻底删除/未输入";
        }
        if(StringUtils.isEmpty(productLine.getProductlineCode())) {
            return "产线编码不能为空";
        }

        if(getByProductLineCode(productLine.getProductlineCode(), productLine.getProductlineId()) != null){
            return "产线编码已存在";
        }
        if(StringUtils.isEmpty(productLine.getProductlineName())) {
            return "产线名称不能为空";
        }
        if(StringUtils.isBlank(productLine.getWorkshopName())){
            return "车间名称为空";
        }
        Map<String, Workshop> workShopMap = uploadMapper.queryWorkShop();
        if(!workShopMap.containsKey(productLine.getWorkshopName())){
            return "车间名称填写错误/不规范";
        }
        Workshop workShop = workShopMap.get(productLine.getWorkshopName());
        productLine.setWorkshopId(workShop.getWorkshopId());
        if(productLine.getProductlineCode().length() > CONTENTLENGTH) {
            return "产线编码字数超过规定长度50";
        }
        if(productLine.getProductlineName().length() > CONTENTLENGTH) {
            return "产线名称字数超过规定长度50";
        }
        if(vcRemark!=null && vcRemark.length() > CONTENTLENGTH) {
            return "说明字数超过规定长度50";
        }


        return null;
    }

}
